package com.agrm.rabc.controller;

import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.rabc.dto.Role;
import com.agrm.rabc.service.RoleService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api/v1/roles", produces = MediaType.APPLICATION_JSON_VALUE)
public class RoleApi {
    private RoleService roleService;

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @GetMapping
    public ResponseResult findAll(Role role,
                                  @RequestParam(defaultValue = "1") Integer pageNo,
                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Role> page = new Page<>(pageNo, pageSize);
        page = roleService.findAll(role, page);
        return ResponseResult.okResult(page);
    }

    @GetMapping("/id/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id) {
        Role role = roleService.findById(id);
        if (role == null) {
            return ResponseResult.errorResult(-1,"未查询到指定编号的角色");
        } else {
            return ResponseResult.okResult(role);
        }
    }

    @PostMapping
    public ResponseResult save(@RequestBody Role role) {
        boolean success = roleService.save(role);
        if (success) {
            return ResponseResult.okResult(200,"");
        } else {
            return ResponseResult.errorResult(-1,"保存角色失败");
        }
    }

    @PutMapping
    public ResponseResult update(@RequestBody Role role) {
        boolean success = roleService.update(role);
        if (success) {
            return ResponseResult.okResult(200,"");
        } else {
            return ResponseResult.errorResult(-1,"修改角色失败");
        }
    }

    @DeleteMapping
    public ResponseResult deleteByIds(@RequestBody Integer[] ids) {
        int count = roleService.deleteByIds(List.of(ids));
        if (count > 0) {
            return ResponseResult.okResult(count);
        } else {
            return ResponseResult.errorResult(-1,"删除角色失败");
        }
    }
}
